package com.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wechat.common.OkHttpUtils;
import com.wechat.common.RedisUtil;
import com.wechat.entity.WechatUser;
import com.wechat.service.WechatUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Controller
public class DemoController {

    private static Logger logger = LoggerFactory.getLogger(DemoController.class);

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.secret}")
    private String secret;

    @Value("${wechat.redirect_uri}")
    private String redirect_uri;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private WechatUserService wechatUserService;

    public String getUserInfo(String code){
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";

        HashMap<String,String> params = new HashMap<>();
        params.put("appid",appId);
        params.put("secret",secret);
        params.put("code",code);
        params.put("grant_type","authorization_code");

        String result = null;
        try {
            result = OkHttpUtils.getInstance().get(url,params);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject object = JSON.parseObject(result);
        String access_token = object.getString("access_token");
        String openId = object.getString("openid");
        logger.info("Code换取Token信息-->【{}】",object.toJSONString());

        String infoUrl = "https://api.weixin.qq.com/sns/userinfo";

        HashMap<String,String> infoParam = new HashMap<>();
        infoParam.put("access_token",access_token);
        infoParam.put("openid",openId);
        infoParam.put("lang","zh_CN");
        String info = null;
        try {
            info = OkHttpUtils.getInstance().get(infoUrl,infoParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }


    @GetMapping("/auth")
    public String getCode(@RequestParam("code") String code, HttpServletRequest request, ModelMap modelMap) {

        logger.info("code={}", code);
        String userInfo = getUserInfo(code);
        WechatUser user = null;
        user = JSONObject.parseObject(userInfo,WechatUser.class);
        user.setUnionId("");
        logger.info("信息:【{}】",JSONObject.toJSONString(user));
        modelMap.addAttribute("user",user);
        if (user != null){
            WechatUser wechatUser = wechatUserService.getUserByOpenId(user.getOpenid());
            if (wechatUser == null){
                wechatUserService.insertUser(user);
            }else {
                wechatUserService.updateUser(user);
            }
        }
        return "/uc"; // 转到uc.html
    }

    @GetMapping("/uc")
    public void auth(HttpServletResponse response) {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid="+ appId +"&" +
                "redirect_uri="+ redirect_uri +"&" +
                "response_type=code&" +
                "scope=snsapi_userinfo&" +
                "state=STATE#wechat_redirect";
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @GetMapping("/user")
    @ResponseBody
    public Object getUser(@RequestParam("openId") String openId){
        return wechatUserService.getUserByOpenId(openId);
    }

    @GetMapping("/user-info")
    public ModelAndView userInfo(String openId, ModelAndView mv){
        WechatUser wechatUser = wechatUserService.getUserByOpenId(openId);
        mv.addObject("user", wechatUser);
        mv.setViewName("/index"); //转到index.html
        return mv;
    }


    @GetMapping("/feedback")
    public ModelAndView feedback(@RequestParam("openId") String openId,@RequestParam("nickname")String nickname, ModelAndView mv){
        mv.addObject("openId", openId);
        mv.addObject("nickname", nickname);
        mv.setViewName("/feedback"); //feedback.html
        return mv;
    }

    @PostMapping("/feedback")
    @ResponseBody
    public String feedback(@RequestParam String openId,@RequestParam String nickname,
                           @RequestParam String feedback){
        logger.info("openId=【{}】,nickname=【{}】,feedback=【{}】",openId,nickname,feedback);

        return "success";
    }

}
